<?php

class Scandirr
{
	private static $_lastFileListFromScandirr = array();
	
	// Clear the last fileList made by scandirr call
	private static function clearFileList()
	{
		Scandirr::$_lastFileListFromScandirr = array();
	}
	
	// Get the last fileList made by scandirr call
	public function getLastFileList()
	{
		return Scandirr::$_lastFileListFromScandirr;
	}
	
	private function process($root, $callback_function = null, $deep = -1)
	{
		if(is_int($callback_function))
		{
			$deep = (int)$callback_function;
			$callback_function = null;
		}
	
		$dir = array();
		if(is_dir($root))
		{
			$dir = scandir($root);
		}
		
		if($deep-- == 0)
		{
			return;
		}
		
		foreach($dir as $entry)
		{
			if($entry != '..' && $entry != '.')
			{
				if(is_dir($root.OS_PATH_SEPARATOR.$entry))
				{
					$this->process($root.OS_PATH_SEPARATOR.$entry, $callback_function, $deep);
				}
				
				Scandirr::$_lastFileListFromScandirr[] = $root.OS_PATH_SEPARATOR.$entry;
				if(!is_null($callback_function))
				{
					$return = $callback_function($root.OS_PATH_SEPARATOR.$entry);
					if($return === false)
					{
						return false;
					}
				}
			}
		}
	}
	
	// Scandir like function with recursive capability and which use callback_function
	public function __construct($root, $callback_function = null, $deep = -1)
	{
		$this->clearFileList();
		if($this->process($root, $callback_function, $deep) === false)
		{
			throw new Exception('Callback function returns false');
		}
	}
}
